package com.tq68.weixin.controller.login;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.jfinal.core.Controller;
import com.jfinal.kit.PropKit;
import com.tq68.weixin.common.AppConstantEnum;
import com.tq68.weixin.model.Bbs;
import com.tq68.weixin.model.Checkin;
import com.tq68.weixin.model.Community;
import com.tq68.weixin.model.CommunityAlias;
import com.tq68.weixin.model.User;
import com.tq68.weixin.model.UserCommunity;
import com.tq68.weixin.utils.DateUtils;
import com.tq68.weixin.utils.JssdkParamUtil;
import com.tq68.weixin.vo.JssdkVO;
import com.tq68.weixin.vo.UserVO;

public class NewuserController extends Controller{

	public void index(){
		render("index.html");
	}
	
	public void startStep(){
		JssdkParamUtil jpu = new JssdkParamUtil();
		JssdkVO jssdk = jpu.getWebParam(getRequest().getRequestURL().toString());
		if(jssdk.getErrorMsg()==null){
			setAttr("noncestr", jssdk.getNonceStr());
	        setAttr("timestamp", jssdk.getTimestamp());
	        setAttr("signature",jssdk.getSignature());
			setAttr("appId", PropKit.get("appId"));
	        setAttr("baiduAK", PropKit.get("baiduAK"));
		}else{
			setAttr("errorMsg",jssdk.getErrorMsg());
		}
		render("startStep.html");
	}
	
	public void saveNewuser(){
		String commName = getPara("commName");
		String commAddress = getPara("commAddress");
		String lng = getPara("lng");
		String lat = getPara("lat");
		String homeTown = getPara("homeTown");
		UserVO uservo = getSessionAttr("uservo");
		User user = User.dao.getUserByWeixinOpenid(uservo.getOpenid());
		if(user!=null){
			//根据小区名称判断是否已保存此小区，未保存则存入库
			Community comm = Community.dao.getCommunityByAlias(commName);
			if(comm==null){
				comm = new Community();
				comm.setCommName(commName);
				comm.setCommAddress(commAddress);
				comm.save();
				CommunityAlias alias = new CommunityAlias();
				alias.setAlias(commName);
				alias.setAliasAddress(commAddress);
				alias.setCommid(comm.getId());
				alias.save();
			}
			//添加业主与小区关联关系表
			UserCommunity uc = new UserCommunity();
			uc.setUserid(user.getId());
			uc.setCommunityid(comm.getId());
			uc.save();
			//添加用户的打卡信息
			Checkin ch = new Checkin();
			ch.setLatitude(lat);
			ch.setLongitude(lng);
			ch.setCheckCommid(comm.getId());
			ch.setCheckCommname(comm.getCommName());
			ch.setCheckAliasCommid(CommunityAlias.dao.getCommunityAliasByAlias(commName).getId());
			ch.setCheckAliasCommname(commName);
			ch.setChecktime(DateUtils.toTimeStr(new Date()));
			ch.setNickname(user.getNickname());
			ch.setUserid(user.getId());
			ch.setUsercommid(uc.getId());
			ch.save();
			//更新用户表的小区信息和最后打卡日期，目前一个用户只属于一个小区
			user.setUserCommId(comm.getId());
			user.setUserCommName(commName);
			user.setLastCheckinDate(DateUtils.toDateStr(new Date()));
			//更新新用户信息
			user.setHomeTown(homeTown);
			//打了一次卡就升级为一级村民
			user.setUserlevel(Integer.parseInt(AppConstantEnum.UserLevel.Level1.getCode()));
			user.update();
			//更新周周期开始时间，周周期打卡次数以及总打卡次数
			uc.setCheckinWeekCount((uc.getCheckinWeekCount()!=null?uc.getCheckinWeekCount():0)+1);
			uc.setCheckinTotalCount((uc.getCheckinTotalCount()!=null?uc.getCheckinTotalCount():0)+1);
			if(uc.getCheckinWeekTime()==null){
				uc.setCheckinWeekTime(DateUtils.toTimeStr(new Date()));
			}
			uc.update();
			//这是用户第一次打卡，更新信息到session
			uservo.setUserCommunityId(comm.getId());
			uservo.setUserCommunityName(commName);
			uservo.setCommunityNameAlias(CommunityAlias.dao.getCommunityAlias(user.getUserCommId()));
			uservo.setUsercommid(uc.getId());
			uservo.setLastCheckinDate(user.getLastCheckinDate());
			uservo.setCheckinToday(DateUtils.toDateStr(new Date()).equals(user.getLastCheckinDate())?true:false);
			uservo.setUserlevel(user.getUserlevel());
			uservo.setUserlevelStr(AppConstantEnum.UserLevel.codeMap.get(user.getUserlevel()+""));
			uservo.setLevelColor(user.getUserlevel());
			uservo.setCoins(user.getGoldcoin());
			uservo.setCvalue(user.getContributionValue());
			uservo.setHomeTown(user.getHomeTown());
			uservo.setProvince();
			uservo.setCity();
			uservo.setDistin();
			uservo.setSameHometownCount(User.dao.getUserCountByHometownAndCommid(user.getHomeTown(), user.getUserCommId()));

			//更新最近的打卡记录
			List<Checkin> checklist = new ArrayList<Checkin>();
			checklist.add(0, ch);
			uservo.setRecentlyChecklist(checklist);
			setSessionAttr("uservo", uservo);
			render("finalStep.html");
		}else{
			render("index.html");
		}
	}
	
	public void completeFinalStep(){
		UserVO uservo = getSessionAttr("uservo");
		String comments = "大家好，我来自"+uservo.getCity()+"·"+uservo.getDistin();
		Integer tag = Integer.parseInt(AppConstantEnum.BbsCategory.Townee.getCode());
		String tagname = AppConstantEnum.BbsCategory.Townee.getName();
		Integer forumSubject = Integer.parseInt(AppConstantEnum.SubjectType.Others.getCode()); //其他类主题
		Integer userid = uservo.getUserid();
		String nickname = uservo.getNickname();
		Integer userlevel = uservo.getUserlevel();
		Bbs bbs = new Bbs();
		bbs.setForumSubject(forumSubject);
		bbs.setContent(comments);
		bbs.setAddtime(DateUtils.toTimeStr(new Date()));
		bbs.setMainpicPath("");
		bbs.setUserid(userid);
		bbs.setNickname(nickname);
		bbs.setUserlevel(userlevel);
		bbs.setTagsname(tagname);
		bbs.setCategory(tag);
		bbs.setCommuid(uservo.getUserCommunityId());
		bbs.setCommuName(uservo.getUserCommunityName());
		bbs.setStatus(Integer.parseInt(AppConstantEnum.BbsStatus.Active.getCode()));
		bbs.save();
		redirect("/communityChat");
	}
}
